package com.starchen.optimalselection.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.admin.mapper.AdminUserMapper;
import com.starchen.optimalselection.admin.model.AdminUser;
import com.starchen.optimalselection.admin.model.form.LoginForm;
import com.starchen.optimalselection.admin.model.vo.LoginVo;
import com.starchen.optimalselection.admin.model.vo.RouterVo;
import com.starchen.optimalselection.admin.service.AdminMenuService;
import com.starchen.optimalselection.admin.service.AdminUserService;
import com.starchen.optimalselection.common.exception.CustomException;
import com.starchen.optimalselection.common.model.QueryParamsForm;
import com.starchen.optimalselection.common.model.ResultPage;
import com.starchen.optimalselection.common.utils.PageUtils;
import com.starchen.optimalselection.common.utils.ResponseEnum;
import com.starchen.optimalselection.config.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author daxilong
 * @since 2022-09-28
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminMenuService adminMenuService;

//    @Autowired
//    private LoginLogService loginLogService;

    @Override
    public ResultPage selectPage(QueryParamsForm queryParamsVo) {

        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();

        String keyword = queryParamsVo.getKeyword();

        if(StringUtils.hasText(keyword)){
            queryWrapper.like("username",keyword).or().like("nick_name",keyword).or().like("phone",keyword);
        }

        IPage<AdminUser> pageModel = baseMapper.selectPage(PageUtils.getPage(queryParamsVo.getPageIndex(),queryParamsVo.getPageSize()),queryWrapper);

        return new ResultPage(pageModel);
    }

    @Override
    public AdminUser getUserInfoByUserName(String username) {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return baseMapper.selectOne(wrapper);
    }

    //根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限数据）
    @Override
    public Map<String, Object> getUserInfo(String username) {
        //根据username查询用户基本信息
        AdminUser sysUser = this.getUserInfoByUserName(username);

        List<RouterVo> routerVos= adminMenuService.findMenusByUserId(sysUser.getId());
        //根据userid查询按钮权限值
        List<String> permsList = adminMenuService.getUserButtonList(sysUser.getId());

        Map<String,Object> result = new HashMap<>();
        result.put("name",username);
        result.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        //菜单权限数据
        result.put("routers",routerVos);
        //按钮权限数据
        result.put("buttons",permsList);
        return result;
    }

    @Override
    public LoginVo login(LoginForm loginVo, String ipAddress) {

        AdminUser sysUser = findUserByUsername(loginVo.getUsername());
        if(sysUser == null){
            throw new CustomException(ResponseEnum.LOGIN_MOBILE_ERROR);
        }

        if(!passwordEncoder.matches(loginVo.getPassword(),sysUser.getPassword())){
            throw new CustomException(ResponseEnum.PASSWORD_ERROR);
        }

        if(sysUser.getStatus() == 0){
            throw new CustomException(ResponseEnum.ACCOUNT_STOP);
        }
        String token = jwtTokenUtil.generateToken(sysUser.getUsername());

        //根据用户名修改登录时间
        //updateLoginTimeByUsername(username);
        //loginLogService.recordLoginLog(adminUserDetails.getUsername(),1,ipAddress,"登录成功");
        LoginVo login = new LoginVo();
        login.setToken(token);
        return login;
    }

    @Override
    public AdminUser findUserByUsername(String username){

        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        AdminUser user = baseMapper.selectOne(wrapper);

        if(user != null){
            return user;
        }
        throw new CustomException(ResponseEnum.LOGIN_MOBILE_ERROR);
    }

//    @Override
//    public void updateUser(SysUser sysUser) {
//        String encodePassword = passwordEncoder.encode(sysUser.getPassword());
//        sysUser.setPassword(encodePassword);
//        sysUser.setStatus(1);
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("id",sysUser.getId());
//        queryWrapper.select("username","name","phone");
//
//        baseMapper.update(sysUser,queryWrapper);
//    }

    @Override
    public void logout(String username) {
        //清空缓存中的用户相关数据
        //redisTemplate.delete(username);
    }

}
